package com.example.controller.admin;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.entity.UserInfo;
import com.example.service.UserInfoService;
import com.example.utils.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.List;

/**
 * 客户信息管理控制器
 */
@Controller
@RequestMapping("/admin/user")
public class UserInfoController {

    @Autowired
    private UserInfoService userInfoService;

    /**
     * 客户管理页面
     */
    @GetMapping("/page")
    public String userPage() {
        return "admin/user/index";
    }

    /**
     * 获取客户列表
     */
    @GetMapping("/list")
    @ResponseBody
    public Result<Page<UserInfo>> list(
            @RequestParam(value = "page", defaultValue = "1") Integer page,
            @RequestParam(value = "limit", defaultValue = "10") Integer limit,
            @RequestParam(value = "keyword", required = false) String keyword) {
        
        Page<UserInfo> pageParam = new Page<>(page, limit);
        LambdaQueryWrapper<UserInfo> queryWrapper = new LambdaQueryWrapper<>();
        
        if (StringUtils.isNotBlank(keyword)) {
            queryWrapper.like(UserInfo::getCustomerName, keyword)
                    .or()
                    .like(UserInfo::getPid, keyword)
                    .or()
                    .like(UserInfo::getTelephone, keyword);
        }
        
        Page<UserInfo> pageResult = userInfoService.page(pageParam, queryWrapper);
        return Result.success(pageResult);
    }

    /**
     * 添加客户
     */
    @PostMapping("/add")
    @ResponseBody
    public Result<?> add(
            @RequestParam("customerName") String customerName,
            @RequestParam("pid") String pid,
            @RequestParam(value = "telephone", required = false) String telephone,
            @RequestParam(value = "address", required = false) String address) {
        
        UserInfo userInfo = new UserInfo();
        userInfo.setCustomerName(customerName);
        userInfo.setPid(pid);
        userInfo.setTelephone(telephone);
        userInfo.setAddress(address);
        
        boolean saved = userInfoService.save(userInfo);
        if (saved) {
            return Result.success("添加成功");
        } else {
            return Result.error("添加失败");
        }
    }

    /**
     * 修改客户
     */
    @PostMapping("/update")
    @ResponseBody
    public Result<?> update(
            @RequestParam("customerId") Integer customerId,
            @RequestParam("customerName") String customerName,
            @RequestParam("pid") String pid,
            @RequestParam(value = "telephone", required = false) String telephone,
            @RequestParam(value = "address", required = false) String address) {
        
        UserInfo userInfo = new UserInfo();
        userInfo.setCustomerId(customerId);
        userInfo.setCustomerName(customerName);
        userInfo.setPid(pid);
        userInfo.setTelephone(telephone);
        userInfo.setAddress(address);
        
        boolean updated = userInfoService.updateById(userInfo);
        if (updated) {
            return Result.success("修改成功");
        } else {
            return Result.error("修改失败");
        }
    }

    /**
     * 删除客户
     */
    @DeleteMapping("/delete/{id}")
    @ResponseBody
    public Result<?> delete(@PathVariable("id") Integer id) {
        boolean removed = userInfoService.removeById(id);
        if (removed) {
            return Result.success("删除成功");
        } else {
            return Result.error("删除失败");
        }
    }

    /**
     * 获取客户信息
     */
    @GetMapping("/info/{id}")
    @ResponseBody
    public Result<UserInfo> info(@PathVariable("id") Integer id) {
        UserInfo userInfo = userInfoService.getById(id);
        if (userInfo != null) {
            return Result.success(userInfo);
        } else {
            return Result.error("客户不存在");
        }
    }

    /**
     * 导出客户数据
     */
    @GetMapping("/export")
    public void export(HttpServletResponse response) throws IOException {
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        String fileName = URLEncoder.encode("客户信息", "UTF-8");
        response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
        
        List<UserInfo> list = userInfoService.list();
        EasyExcel.write(response.getOutputStream(), UserInfo.class).sheet("客户信息").doWrite(list);
    }
} 